<?php

namespace App\Models;

use App\Models\Channel;
use App\Models\LiveProgram;
use App\Models\QQAlbum;
use App\Models\QQAlbumVideo;
use Log;
use Cache;
use App\Common\Tools;

class VoiceSearchVod
{
    public function searchTVAndVod($text)
    {
        if (preg_match('/^我(要|想)看(\S+)/', $text, $matches) && isset($matches[2])) {
            $key = trim($matches[2]);
            $channelObjs = Channel::where("name", $key)->limit(10)->get();
            if ($channelObjs && count($channelObjs) > 0) {
                $channels = [];
                foreach ($channelObjs as $key => $channelObj) {
                    $channels[$key] = [
                        'model' => 'channel',
                        'name' => $channelObj->name,
                        'code' => $channelObj->code,
                        'logo' => $channelObj->logo,
                        'tags' => $channelObj->tags,
                        'hot' => $channelObj->hot,
                        'targetActions' => $this->getTargetActionObjsByChannelCode($channelObj->code),
                        'liveProgram' => $this->getLiveProgramByChannelCode($channelObj->code)
                    ];
                }
                return [
                    'status' => 0,
                    'message' => '',
                    'datas' => $channels
                ];
            }
            $liveProgramObjs = LiveProgram::where("program_name", $key)->orWhere('wiki_title', $key)->limit(10)->get();
            if ($liveProgramObjs && count($liveProgramObjs) > 0) {
                \Log::info('search liveProgram');
                $livePrograms = [];
                foreach ($liveProgramObjs as $key => $liveProgramObj) {
                    $livePrograms[$key] = [
                        'model' => 'live',
                        'programName' => $liveProgramObj->program_name,
                        'channelCode' => $liveProgramObj->channel_code,
                        'startTime' => date('Y-m-d H:i:s', $liveProgramObj->start_time),
                        'endTime' => date('Y-m-d H:i:s', $liveProgramObj->end_time),
                        'wikiID' => $liveProgramObj->wiki_id,
                        "wikiTitle" => $liveProgramObj->wiki_title,
                        "wikiCover" => Tools::getWikiCover($liveProgramObj->wiki_cover),
                        'tags' => $liveProgramObj->tags,
                        'hot' => $liveProgramObj->hot,
                        'targetActions' => $this->getTargetActionObjsByChannelCode($liveProgramObj->channel_code),
                    ];
                }
                return [
                    'status' => 0,
                    'message' => '',
                    'datas' => $livePrograms
                ];
            }
            $key = str_replace(['的'], '', $key);
            $xs = new \XS(config_path('./album.ini'));
            $docs = $xs->search->setSort('score')->setLimit(10)->search($key);
            $count = $xs->search->lastCount;
            if (!$count) {
                return [
                    'status' => 1002,
                    'message' => '没有找到你想要的结果!'
                ];
            }

            $datas = [];
            foreach ($docs as $key => $doc) {
                $datas[$key] = $this->formatXsAlbum2AI($doc);
            }
            return [
                'status' => 0,
                'message' => '',
                'datas' => $datas
            ];
        } else {
            return [
                'status' => 1002,
                'message' => '没有找到你想要的结果!'
            ];
        }
    }

    public function searchVideo($text, $matches)
    {
        if(!isset($matches[3])) {
            return [
                'status' => 1002,
                'message' => '没有找到你想要的结果!'
            ];
        }
        $key = trim($matches[2]);
        $num = Tools::cnNum2Num(trim($matches[3]));
        $key = str_replace(['的'], '', $key);
        $xs = new \XS(config_path('./album.ini'));
        $docs = $xs->search->setSort('score')->setLimit(10)->search($key);
        $count = $xs->search->lastCount;
        if (!$count) {
            return [
                'status' => 1002,
                'message' => '没有找到你想要的结果!'
            ];
        }
        $doc = $docs[0];
        $qqAlbumVideo = QQAlbumVideo::where("album_id", $doc->album_id)
            ->where('play_order', $num)->first();
        if (!$qqAlbumVideo) {
            return [
                'status' => 1002,
                'message' => '没有找到你想要的结果!'
            ];
        } else {
            $datas = [];
            $datas[0] = $this->formatQQAlbumVideo2AI($qqAlbumVideo);
            return [
                'status' => 0,
                'message' => '',
                'datas' => $datas
            ];
        }
    }

    protected function getLiveProgramByChannelCode($channel_code)
    {
        $liveProgram = LiveProgram::where('channel_code', $channel_code)->first();
        if ($liveProgram) {
            return [
                "name" => $liveProgram->program_name,
                "start_time" => date("Y-m-d H:i:s", $liveProgram->start_time),
                "end_time" => date("Y-m-d H:i:s", $liveProgram->end_time),
                "wiki_id" => $liveProgram->wiki_id,
                "wiki_title" => $liveProgram->wiki_title,
                "wiki_cover" => Tools::getWikiCover($liveProgram->wiki_cover),
                "next_name" => "",
                "next_wiki_id" => ""
            ];
        } else {
            return null;
        }
    }

    protected function getTargetActionObjsByChannelCode($channel_code)
    {
        $key = 'ChannelTargetActions_' . $channel_code;
        if (Cache::has($key)) {
            return Cache::get($key);
        } else {
            $targetActions = [];
            $targetActionObjs = HdpChannel::where("channel_code", $channel_code)->get();
            if ($targetActionObjs) {
                foreach ($targetActionObjs as $targetActionObj) {
                    array_push($targetActions, $this->formatHDPChannel2AI($targetActionObj));
                }
            }
            Cache::put($key, $targetActions);
            return $targetActions;
        }
    }

    protected function formatHDPChannel2AI($channel)
    {
        return [
            'active_type' => 'activity',
            'name' => $channel->name,
            'package_name' => 'hdpfans.com',
            'class_name' => 'hdp.player.StartActivity',
            'extra' => [
                ['key' => "ChannelNum", 'value' => $channel->num]
            ]
        ];
    }

    protected function formatXsAlbum2AI($doc)
    {
        return [
            'model' => 'album',
            'name' => $doc->albumName,
            'verpic' => $doc->albumVerpic,
            'horpic' => $doc->albumHorpic,
            'targetActions' => [
                [
                    'active_type' => 'action',
                    'package_name' => 'com.ktcp.tvvideo',
                    'action_name' => 'om.tencent.qqlivetv.open',
                    'extra' => [
                        ['uri' => 'tenvideo2://?action=1&cover_id=' . $doc->album_id . '&pull_from=101503']
                    ]
                ]
            ]
        ];
    }

    protected function formatQQAlbumVideo2AI($video)
    {
        return [
            'model' => 'albumVideo',
            'name' => $video->video_name,
            'album_id' => $video->album_id,
            'video_id' => $video->video_id,
            'verpic' => $video->video_verpic,
            'horpic' => $video->video_horpic,
            'targetActions' => [
                [
                    'active_type' => 'action',
                    'package_name' => 'com.ktcp.video',
                    'action_name' => 'com.tencent.qqlivetv.open',
                    'extra' => [
                        ['uri' => 'uri="tenvideo2://?action=7&video_id=' . $video->video_id . '&video_name=' . $video->video_name . '&cover_id=' . $video->album_id . '&cover_pulltype=1"']
                    ]
                ]
            ]
        ];
    }

    public function getVarietyHots()
    {
        return $this->getHots('variety');
    }

    public function getTvHots()
    {
        return $this->getHots('tv');
    }

    public function getMovieHots()
    {
        return $this->getHots('movie');
    }

    public function getCartoonHots()
    {
        return $this->getHots('cartoon');
    }

    public function getDocHots()
    {
        return $this->getHots('doc');
    }

    public function getHots($type)
    {
        $albums = QQAlbum::where('type', $type)->orderBy('hot_num', 'desc')->take(10)->get();
        if($albums) {
            foreach ($albums as $key => $album) {
                $wiki = [
                    'model' => 'album',
                    'album_id' => $album->album_id,
                    'album_name' => $album->album_name,
                    'type' => $album->type,
                    'tags' => $album->sub_type,
                    'album_verpic' => $album->album_verpic,
                    'hot_num' => $album->hot_num,
                    'targetActions' => [$this->formatQQAlbum2AI($album)],
                ];
                $wikis[$key] = $wiki;
            }
        }
        return [
            'status' => 0,
            'message' => '',
            'datas' => $wikis
        ];
    }

    protected function formatQQAlbum2AI($album)
    {

        return [
            'active_type' => 'action',
            'package_name' => 'com.ktcp.tvvideo',
            'action_name' => 'om.tencent.qqlivetv.open',
            'extra' => [
                ['uri' => 'tenvideo2://?action=1&cover_id=' . $album->album_id . '&pull_from=101503']
            ]
        ];
    }
}
